package com.dhcc.core.framework.security.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.dhcc.core.framework.log.LogManager;
import com.dhcc.core.framework.log.factory.LogTaskFactory;
import com.dhcc.core.framework.security.ShiroKit;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.modules.system.entity.UserOnline;

import io.buji.pac4j.filter.LogoutFilter;

/**
 * Pac4jLogoutFilter
 */
public class Pac4jLogoutFilter extends LogoutFilter {
    /**
     * 是否是前台
     */
    private Boolean isFront;

    @Override
    public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String clientName = httpServletRequest.getParameter("client_name");
        if(CommonUtil.equals(clientName, "form")){
            this.setDefaultUrl("/login");
        }
        super.doFilter(servletRequest, servletResponse, filterChain);
        UserOnline userOnline = ShiroKit.getCurrentUserOnline();
        if (CommonUtil.isNotEmpty(userOnline)) {
            // 记录用户退出日志
            if(isFront){
                LogManager.me().executeLog(LogTaskFactory.frontLogoutLog(userOnline));
            }else{
                LogManager.me().executeLog(LogTaskFactory.backendLogoutLog(userOnline));
            }
        }
    }

    public Boolean getIsFront() {
        return isFront;
    }

    public void setIsFront(Boolean isFront) {
        this.isFront = isFront;
    }
}
